class MyTeacherList {
    constructor() {

        this.rankList = {};
        this.selectedHtml;
        this.tableId = "body-teacher-tab-table";

        this.tableBtnDistabled = 'layui-btn-disabled';

        var load = this;
        this.addLayerindex = 0;

        this.tableSetup = {
            id: "body-teacher-tab-table",//"body-teacher-tab-table-setup-id",
            elem: '#body-teacher-tab-table'
            , defaultToolbar: ['filter', 'print', 'exports']
            // , height: 312
            , url: '/Lock/GetSomeAcc' //数据接口
            , where: { idCard: this.idCard, accrank: 2 }
            , page: true    //开启分页
            , toolbar: '#toolBar'
            , cols: [[ //表头
                { field: 'aid', title: 'ID', width: '10%',edit: "text", sort: true, /*fixed: 'left'*/ }
                , { field: 'tname', title: '姓名', edit: "text", width: '10%' }
                , {
                    field: 'tsex', title: '性别',
                    templet: function (d) {
                        var tmpTrue = "", tmpFalse = "", str = "selected";
                        var htmlstr = "<form class='layui-form'><select name='SexSelect' value=" + d.tsex + " >";
                        console.log("--------------- sex --------------");
                        console.log(d.tsex);
                        if (d.tsex) tmpTrue = str;
                        else tmpFalse = str;
                        htmlstr += "<option value=" + true + " " + tmpTrue + ">男</option>";

                        htmlstr += "<option value=" + false + " " + tmpFalse + ">女</option>";

                        htmlstr += "</select></form>";

                        return htmlstr;

                    }
                    , width: '10%'
                }
                , {
                    field: 'rid', title: '职称',
                    templet: function (d) {
                        return this.selectedHtml;

                    }
                    , width: '10%', sort: true
                }
                , {
                    field: 'tage', title: '年龄', edit: "text",
                    templet: function (d) {
                        if (d.tage == -1) return "";
                        else return d.tage;
                    }
                    , width: '10%', sort: true
                }
                , { field: 'tsalary', title: '工资', width: '20%', edit: "text", sort: true }
                , { field: 'rpiece', title: '提成基数', width: '10%', sort: true }
                , {
                    field: 'edit', title: '编辑',
                    templet: "#tool-col-exit"
                    , width: '20%', sort: true, align: "center"
                }
            ]]
            , contentType: 'jsonp'//一定要是jsonp类型
            , parseData: function (res) { //res 即为原始返回的数据

                // console.log(res.status)
                console.log("myteacher+:")
                console.log(res);

                return {
                    "code": res.statue, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.teachers //解析数据列表
                };
            }
            , request: {
                pageName: 'pageInd' //页码的参数名称，默认：page
                , limitName: 'rowCount' //每页数据量的参数名，默认：limit
            }
            , done: function (res, curr, count) {

                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                console.log("done-------------------------");
                console.log(res);
                var data = res.data;
                var len = data = data.length;

                var elem = $("select[name=ridSelect]");

                console.log(elem);

                for (let i = 0; i < len; i++) {
                    console.log("--------------- doing -------------")
                    let select = 'dd[lay-value=' + res.data[i].rid + ']';
                    console.log(res.data[i].rid);
                    let temp = $(elem[i]).siblings("div.layui-form-select").find('dl').find(select).click();
                    load.stopEditBtn(elem[i]);
                    console.log(temp);
                }

                // layui.use("form",function(){
                //     layui.form.render("select");
                // })



            }
        }


    }

    start() {
        this.render();
        this.addForm();
    }

    render() {

        var load = this;

        $.get("/Lock/GetALLRank", { data: 100 }, function (resp) {
            console.log("GetALLRank");
            console.log(resp);

            resp = resp.ranks;

            load.selectedHtml = "<form class='layui-form'><select name='ridSelect' >";

            let addSelectHtml = "";

            for (let e in resp) {
                let str =  "<option value=" + resp[e].rname + ">" + resp[e].rname + "</option>";
                load.rankList[resp[e].rname] = { 'rid': resp[e].rid, 'rpiece': resp[e].rpiece };
                load.selectedHtml += str;
                addSelectHtml += str;
            }

            load.selectedHtml += "</select></form>";

            // 添加表单中的下拉宽渲染
            console.log( $("#id-body-teachcer-tab-table-add-form select[name=rid]"));
            let addSelectDom= $("#id-body-teachcer-tab-table-add-form select[name=rid]");
            addSelectDom.html(addSelectHtml);

            layui.form.render("select");


            console.log(load.rankList);

            console.log(load.selectedHtml);

            layui.use(['table', 'form'], function () {
                var table = layui.table;

                var form = layui.form;

                load.tableSetup.cols[0][3].templet = load.selectedHtml;//设置面板

                //第一个实例
                table.render(load.tableSetup);

                table.on('tool(filter-body-teacher-tab-table)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

                    var layEvent = obj.event;
                    var data = obj.data;

                    var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）


                    var btnLoad = this;


                    if (layEvent === 'edit') { //编辑
                        console.log("edit-------------------------");

                        if ($(btnLoad).prop("class").indexOf(load.tableBtnDistabled) != -1) {
                            console.log("disabled");
                            return;
                        }

                        let editLoad = this;

                        let flag = false;


                        layer.confirm('确认修改？', { icon: 3, title: '提示' }, function (index) {
                            $(btnLoad).addClass("layui-btn-disabled");

                            // console.log( $("div[lay-id=body-teacher-tab-table]").find("tr td a.layui-btn-disabled"));
                            console.log($("div[lay-id=body-teacher-tab-table]").find("tr td a.layui-btn-xs")[0]);

                            layer.close(index);//关闭弹出层


                            //同步更新缓存对应的值
                            let select = $(editLoad).parents("tr").find("dd[class=layui-this]");//.attr("lay-value");
                            console.log("vak");
                            // console.log(val);
                            let tsex = select.eq(0).attr("lay-value");
                            let trid = select.eq(1).attr("lay-value");

                            data["rid"] = trid;
                            data["tsex"] = (tsex == "true" ? true : false);
                            console.log(tsex);
                            console.log(trid);
                            console.log(data);
                            // 对后端发出更新请求
                            $.ajaxSetup({ contentType: "application/json; charset=utf-8" });
                            $.get("/Lock/Update/Acc/Teacher", { "teacher": JSON.stringify(data) }, function (resp) {
                                if (resp.statue == 0) {
                                    flag = true;
                                    layer.msg(resp.message, { icon: 6 });
                                } else {
                                    layer.msg(resp.message, { icon: 5 });
                                }
                            })

                            if (!flag) {
                                load.render();
                                return;
                            }

                            obj.update({
                                rpiece: load.rankList[trid].rpiece
                            });

                        });

                        //do something
                        // console.log("tr");
                        // console.log(tr[0]);
                        // console.log(data);
                        // console.log(this);
                        // console.log(load.getIndex(this));   


                    } else if (layEvent === 'logout') {

                        let flag = false;

                        layer.confirm('确认注销用户吗？', function (index) {

                            layer.close(index);
                            //向服务端发送删除指令
                            $.get("/Lock/Delete/Acc/Teacher", { 'aid': data['aid'] }, function (resp) {
                                if (resp.statue == 0) {
                                    flag = true;
                                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                    load.render();
                                    layer.msg(resp.message, { icon: 6 });

                                } else {
                                    layer.msg(resp.message, { icon: 5 });
                                }
                            })

                        });

                    }
                });


                table.on('edit(filter-body-teacher-tab-table)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"

                    // console.log(obj.value); //得到修改后的值
                    // console.log(obj.field); //当前编辑的字段名
                    // console.log(obj.data); //所在行的所有相关数据  
                    console.log("edit");
                    console.log(this);
                    load.startEditBtn(this);

                });


                form.on("select", function () {
                    load.startEditBtn(this);
                });


                //触发事件
                table.on('toolbar(filter-body-teacher-tab-table)', function (obj) {
                    var id =(obj.config.id);                   
                    switch (obj.event) {
                        case 'add':
                            console.log(load.getTr(id));
                            load.addLayerindex=layer.open({
                                type: 1,
                                shade: 0,
                                content: $('#id-body-teachcer-tab-table-add'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                              });
                            
                            
                            // layer.msg('添加');
                            break;
                    };
                });


            })//layui

        })


    }

    doLog

    getAddHtml(){
        // htmlstr  = 
    }



    getTr(id){
        return $("div[lay-id="+id+"]").find("tr")[1].cloneNode("deep");
    }


    getIndex(btn) {
        return $(btn).parents("tr").attr("data-index");
    }

    addForm(){


        let load = this;

        $("#id-body-teachcer-tab-table-add-form").on("submit",function(e){
            e.preventDefault();
    
            
            console.log(this);
            var formData = $(this).serializeArray();

            let teacherJson = {};
            
            for(let i =0; i<formData.length;i++){
                console.log(i);
                teacherJson[formData[i]["name"]] = formData[i]["value"];
            }

            // teacherJson["accrank"] = 2;

            console.log(formData);
            console.log(teacherJson);

    
            $.ajax({
                type: "post",
                data: { "teacher": JSON.stringify(teacherJson) },
                url: "/Lock/Add/Acc/Teacher",
                success: function(res){

                    console.log(res);
    
                    if(res.statue == 0){
                        // 添加成功后应该跳转
                        layer.msg(res.message, {icon: 6});  
                       $("#id-body-teachcer-tab-table-add-form bottom[type=reset]").click();
                       console.log($("#id-body-teachcer-tab-table-add-form bottom[type=reset]"));
                        layer.close(load.addLayerindex);
    
                    }else{
                        layer.msg(res.message,{icon: 5,time: 2000});
                    }

                    load.render();
                    
                },
    
                error: function(){
                    console.log("超时");
                }
    
            });
    
            
    
    
        });//加载函数末
    
    }



    startEditBtn(dom) {
        // 获取行索引，且禁用按钮
        var index = $(dom).parents("tr").attr("data-index")
        var btn = $($("div[lay-id=body-teacher-tab-table]").find("tr[data-index=" + index + "] td a[lay-event=edit]"));

        //  console.log("index:" + index);
        //  console.log(btn);

        btn.removeClass("layui-btn-disabled");
    }

    stopEditBtn(dom) {
        console.log("------------------  stopEditBtn start------------------");
        // console.log(dom);
        // 获取行索引，且禁用按钮
        // console.log( $(dom).parents("tr"));
        var index = $(dom).parents("tr").attr("data-index")
        var btn = $($("div[lay-id=body-teacher-tab-table]").find("tr td a[lay-event=edit]")[index])

        // console.log("index:" + index);
        // console.log(btn);

        btn.addClass("layui-btn-disabled");

        console.log("------------------  stopEditBtn end ------------------");
    }

}